package com.ebidding.service;

import com.ebidding.Utils.DateUtil;
import com.ebidding.entity.Orders;
import com.ebidding.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * Resource 与 Autowired 区别
     */
    @Resource
    private RedisTemplate<String, Orders> redisTemplate;

    private String type = "orders_";
    //查询一条订单
    public Orders findOneOrder(String orderId){
        String key = type+orderId;

        boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey){
            System.out.println("从redis中取");
            return redisTemplate.opsForValue().get(key);
        }
        Orders order = ordersMapper.selectByPrimaryKey(orderId);
        System.out.println("从数据库中取");
        redisTemplate.opsForValue().set(key, order, 120, TimeUnit.SECONDS);
        return order;
    }

    //查询所有订单
    public List<Orders> findAllOrders(){
        List<Orders>  orders = ordersMapper.findAllOrders();

        return orders;
    }

    //删除订单
    @Transactional
    public void deleteOrders(String orderId){
        redisTemplate.delete(type+orderId);
        ordersMapper.deleteByPrimaryKey(orderId);
    }

    //新增订单
    @Transactional
    public void createOrders(Orders orders){

        ordersMapper.insert(orders);
        redisTemplate.opsForValue().set(type+orders.getOrderId(),orders);

    }

    //修改订单
    @Transactional
    public void modifyOrders(Orders orders){

        ordersMapper.updateByPrimaryKeySelective(orders);
        redisTemplate.opsForValue().set(type+orders.getOrderId(),orders);
        System.out.println("修改");


    }


}
